<?php
namespace app\appapi\controller;
use think\Controller;
use think\Request;
use think\Db;
use app\appapi\WeShare;

class WeRedenvelopes extends Common

{
    //获取红包寄语
    function getRedenvelopeBlessings(){
        $result = getRedenvelopeBlessings();
        return json_encode(['code'=>10001,'msg'=>'获取数据成功','data'=>$result]);
    }
        /*
     * 创建名片红包（获取微信支付信息）
     * */
    function getRandomRedenvelopePayInfo(){
        if(!$uid = $this->WxApp_User_Id)
        return json_encode(['code'=>10003,'msg'=>'登陆超时']);
        $data = input('post.');
        if(empty($data['amt']) || !$data['amt'] || empty($data['uid']) || !$data['uid'] ||empty($data['num']) || !$data['num'] || empty($data['type']) || !$data['type'])
        return json_encode(['code'=>10002,'msg'=>'创建失败']);
        $num = (!empty($data['num']) || !$data['num'])?$data['num']:mt_rand(0,9);
        $uid = $data['uid'];
        $amount = $data['amt'];
		$type = $data['type'];
        $openid = getUserInfo($uid,'openid');
        $msg = !empty($data['msg'])?$data['msg']:'';
        if(!judgeUserCardInfo($uid))
        return json_encode(['code'=>10002,'msg'=>'请先完善名片信息']);
        $min = 0.1;
        if((($amount/$num)*10) < $min*10)
        return json_encode(['code'=>10002,'msg'=>'红包均额不能低于'.$min.'元']);
        $Fate_amount = generateAppointRedenvelope($amount,$num,$min);//系统配置生成红包缘分值数
        if(!$Fate_amount || !is_array($Fate_amount))
        return json_encode(['code'=>10002,'msg'=>'生成红包失败']);
        // $total_fee = $amount;//不收手续费
        $total_fee = $amount*1.02;//抽佣费率0.02;
        $order_id = generateRandNumbers('super','NB');
        $body = '有赏名片会员充值';
		$weapp = new WeShare(); 
        $wAppconfig = getWxconfig('weAppSystem');//微信小程序配置
        // $wtconfig = getWxconfig('weChatSystem');//获取微信公众号
        // $wtconfig['app_id'] = $wAppconfig['app_id'];//小程序支付用小程序的Appid
        if(!$result = $weapp->getPayJsApi($wAppconfig, $body, $order_id, $total_fee,$openid))//统一走小程序流程
        return json_encode(['code'=>10002,'msg'=>'支付失败']);
		$result['red_id'] = $order_id;
		$result['uid'] = $uid;
        if($this->_generateRedenvelopeOrder($uid,$order_id,$Fate_amount,$amount,$num,$type,$msg))
        return json_encode(['code'=>10001,'msg'=>'ok','data'=>$result]);
        return json_encode(['code'=>10002,'msg'=>'支付失败']);
    }

     /*
     * 创建缘分红包（获取微信支付信息）
     * */
    function getFateRedenvelopePayInfo(){
        if(!$uid = $this->WxApp_User_Id)
        return json_encode(['code'=>10003,'msg'=>'登陆超时']);
        $data = input('post.');
        if(empty($data['amt']) || !$data['amt'] || empty($data['uid']) || !$data['uid'] || empty($data['type']) || !$data['type'])
        return json_encode(['code'=>10002,'msg'=>'创建失败']);
        $uid = $data['uid'];
        $amount = $data['amt'];
		$type = $data['type'];
        $openid = getUserInfo($uid,'openid');
        $msg = !empty($data['msg'])?$data['msg']:'';
        $min = 0.1;
        $minAmt = !empty($data['minAmt'])?$minAmt:$min;
        $maxAmt = !empty($data['minAmt'])?$maxAmt:'';
        if($maxAmt*10 < $minAmt*10)
        return json_encode(['code'=>10002,'msg'=>'红包金额设置错误']);
        $rule = !empty($data['rule'])?$data['rule']:'';
        $maxAmt = $maxAmt?$maxAmt:0;
        if($amount*10 < $maxAmt*10 || $maxAmt<0)
        return json_encode(['code'=>10002,'msg'=>'红包金额设置错误']);
        if($amount*10 < $minAmt*10 || $minAmt<$min)
        return json_encode(['code'=>10002,'msg'=>'红包金额设置错误']);
        // $total_fee = $amount;//不收手续费
        $total_fee = $amount*1.02;//抽佣费率0.02;
        $order_id = generateRandNumbers('super','NBF');
        $rule = json_decode($rule);
        if(!$this->_getAddRedenvelopeFateRule($order_id,$minAmt,$maxAmt,$rule))
        return json_encode(['code'=>10002,'msg'=>'创建失败']);
        $body = '有赏名片会员充值';
		$weapp = new WeShare(); 
        $wAppconfig = getWxconfig('weAppSystem');//微信小程序配置
        // $wtconfig = getWxconfig('weChatSystem');//获取微信公众号
        // $wtconfig['app_id'] = $wAppconfig['app_id'];//小程序支付用小程序的Appid
        if(!$result = $weapp->getPayJsApi($wAppconfig, $body, $order_id, $total_fee,$openid))//统一走小程序流程
        return json_encode(['code'=>10002,'msg'=>'支付失败']);
		$result['red_id'] = $order_id;
		$result['uid'] = $uid;
        if($this->_generateRedenvelopeOrder($uid,$order_id,$Fate_amount,$amount,$num,$type,$msg))
        return json_encode(['code'=>10001,'msg'=>'ok','data'=>$result]);
        return json_encode(['code'=>10002,'msg'=>'支付失败']);
    }
    /*
     * 缘分红包充值（获取微信支付信息）
     * */
    function getFateRedenvelopeRecharge(){
        if(!$uid = $this->WxApp_User_Id)
        return json_encode(['code'=>10003,'msg'=>'登陆超时']);
        $data = input('post.');
        if(empty($data['amt']) || !$data['amt'] || empty($data['uid']) || !$data['uid'] || empty($data['rid']) || !$data['rid'])
        return json_encode(['code'=>10002,'msg'=>'创建失败']);
        $uid = $data['uid'];
        $amount = $data['amt'];
		$rid = $data['rid'];
        $openid = getUserInfo($uid,'openid');
        $min = 0.1;
        $minAmt = !empty($data['minAmt'])?$minAmt:$min;
        if($amount*10 < $minAmt*10 || $minAmt<$min)
        return json_encode(['code'=>10002,'msg'=>'充值失败']);
        // $total_fee = $amount;//不收手续费
        $total_fee = $amount*1.02;//抽佣费率0.02;    
		$order_id = generateRandNumbers('super','NBC');
        $body = '有赏名片会员充值';
		$weapp = new WeShare(); 
        $wAppconfig = getWxconfig('weAppSystem');//微信小程序配置
        // $wtconfig = getWxconfig('weChatSystem');//获取微信公众号
        // $wtconfig['app_id'] = $wAppconfig['app_id'];//小程序支付用小程序的Appid
		//红包充值额外信息
		$attach = [
			'type' => 'RED_RECHARGE',
			'id' => $rid,
		];
		$attach = json_encode($attach);
        if(!$result = $weapp->getPayJsApi($wAppconfig, $body, $order_id, $total_fee,$openid,$attach))//统一走小程序流程
        return json_encode(['code'=>10002,'msg'=>'支付失败']);
		$result['red_id'] = $order_id;
		$result['uid'] = $uid;
        if($this->_getAddRechargeRecord($order_id,$rid,$amount))
        return json_encode(['code'=>10001,'msg'=>'ok','data'=>$result]);
        return json_encode(['code'=>10002,'msg'=>'支付失败']);
    }
	//添加充值记录
	private function _getAddRechargeRecord($order_id,$rid,$amount)
	{
		if(getRedenvelopesRechargeInfo($order_id))
		return false;
		$arr['Recharge_id'] = $order_id;
		$arr['Redenvelopes_id'] = $rid;
		$arr['Amount'] = $amount;
		$arr['State'] = 2;
		$arr['Addtime'] = time();
		try{
            if($re = Db::name('user_recharge_record')->insert($arr))
            return true;
            return false;
		}catch(\Exception $e){
			return false;
        }
	}

    //添加缘分红包规则
    private function _getAddRedenvelopeFateRule($order_id,$minAmt,$maxAmt,$data)
    {
        if(!$order_id || $order_id == '')
        return false;
        if(judgeRedenvelopesFateRule($order_id))
        return false;
			try{
                $arr['Redenvelopes_id'] = $order_id;
                $arr['Min_amount'] = $minAmt;
                $arr['Max_amount'] = $maxAmt;
                $arr['Hometowns'] = $data['Hometowns'];
                $arr['Locations'] = $data['Locations'];
                $arr['Campus'] = $data['Campus'];
                $arr['Industrys'] = $data['Industrys'];
                $arr['Hobbys'] = $data['Hobbys'];
                $arr['Age'] = $data['Age'];
                $arr['Demand'] = $data['Demand'];
                $arr['Languages'] = $data['Languages'];
                $arr['Gender'] = $data['Gender'];
                $arr['Marriage'] = $data['Marriage'];
                $arr['Position'] = $data['Position'];
                $arr['Longitud'] = $data['Longitud'];
                $arr['Latitude'] = $data['Latitude'];
                if($re = Db::name('user_fate_redenvelopes_rule')->Insert($arr))
                return true;
                return false;
			}catch(\Exception $e){
				return false;
            }
    }

     /*
     * 零钱提现
     * */
     function getCashRedenvelopePayWithdrawal(){
        if(!$uid = $this->WxApp_User_Id)
        return json_encode(['code'=>10003,'msg'=>'登陆超时']);
        $data = input('post.');
        if(empty($data['amt']) || !$data['amt'] || empty($data['uid']) || !$data['uid'])
        return json_encode(['code'=>10002,'msg'=>'参数错误']);
        $uid = $data['uid'];
        $amount = $data['amt'];
        $where['User_id'] = ['=',$uid];
        // $where['State'] = ['=',1];
        // $where['Smallchange']  = ['>=',$amount];
        if(!$re = Db::name('user')->where($where)->find())
        return json_encode(['code'=>10002,'msg'=>'提现失败']);
        if($re['State'] != 1)
        return json_encode(['code'=>10002,'msg'=>'账号状态异常']);
        // if($amount<10)
        // return json_encode(['code'=>10002,'msg'=>'请输入正确提现金额']);
        if($re['Smallchange']<$amount)
        return json_encode(['code'=>10002,'msg'=>'零钱余额不足']);
		$cash_amount = 100;
		if(!judgeDiffDays(getdate($re['Cash_time']),getdate(time())) && $re['Cash_amount'] >= $cash_amount)
        return json_encode(['code'=>10002,'msg'=>'您当日提现额度已达到限制']);
		if(judgeDiffDays(getdate($re['Cash_time']),getdate(time())) && $amount>($cash_amount*1-$re['Cash_amount']*1))
		return json_encode(['code'=>10002,'msg'=>'您当日提现额度已达到限制']);
        $openid = $re['Openid'];
        // $wx_cash = 0;//微信收取的手续费
        // $tp_cash = round($amount*0.02,2);//抽佣费率
        // $total_fee = round(($amount - $wx_cash - $wx_cash),2);//平台收取2%手续费
		$total_fee = $amount;//不收取手续费
        if($total_fee<1)
        return json_encode(['code'=>10002,'msg'=>'提现金额过低']);
        $order_id = generateRandNumbers('super','TX');
        $body = '有赏名片会员提现';
		$weapp = new WeShare(); 
        $wAppconfig = getWxconfig('weAppSystem');//微信小程序配置
        // $wtconfig = getWxconfig('weChatSystem');//获取微信公众号
        // $wtconfig['app_id'] = $wAppconfig['app_id'];//小程序支付用小程序的Appid
        $result = $weapp->getPayCashWithdrawal($wAppconfig, $body, $order_id, $total_fee,$openid);//统一走小程序流程
        if($result['return_code'] != 'SUCCESS' || $result['result_code'] != 'SUCCESS')
        return json_encode(['code'=>10002,'msg'=>'提现失败','data'=>$result]);
        try{
            $this->_generateCashOrder($uid,$order_id,$amount);
            writeCretLog('会员提现结果'.$result['return_msg'].'\r\n');
        }catch(Exception $e){
            writeCretLog('创建提现记录'.$e->getMessage().'\r\n');
        }finally{
            return json_encode(['code'=>10001,'msg'=>'提现成功']);
        };
        return json_encode(['code'=>10002,'msg'=>'提现失败']);
    }
    
	//获取某条红包记录
	public function getOneRedenvelopeLet()
	{
		if(!$uid = $this->WxApp_User_Id)
        return json_encode(['code'=>10003,'msg'=>'登陆超时']);
        $data = input('post.');
        if(empty($data['uid']) || !$data['uid'] || empty($data['rid']) || !$data['rid'])
        return json_encode(['code'=>10002,'msg'=>'参数错误']);
        $uid = $data['uid'];
		$rid = $data['rid'];
		$field = '*';
		$where['User_id'] = ['=',$uid];
		$where['Redenvelopes_id'] = ['=',$rid];
		if($re = Db::name('redenvelopes')->where($where)->field($field)->find());
		$re['Code_num'] = getRedenvelopesCodeCount($rid);
		return json_encode(['code'=>10001,'msg'=>'读取成功','data'=>$re]);
		return json_encode(['code'=>10002,'msg'=>'红包已过期']);
	}

	//查询用户是否存在可用红包
	public function getRandomRedenvelopeCodeLet()
	{
		if(!$uid = $this->WxApp_User_Id)
        return json_encode(['code'=>10003,'msg'=>'登陆超时']);
        $data = input('post.');
        if(empty($data['uid']) || !$data['uid'] || empty($data['mid']) || !$data['mid'])
        return json_encode(['code'=>10002,'msg'=>'参数错误']);
		$uid = $data['uid'];
        $mid = $data['mid'];
        $sid = !empty($data['sid'])?$data['sid']:'';
        $rid = !empty($data['rid'])?$data['rid']:'';
        $where['User_id'] = ['=',$mid];
        $field = 'User_id,Head_portrait,Addtime,State,Username,State';
        if(!$re = Db::name('user')->where($where)->field($field)->find())
		return json_encode(['code'=>10002,'msg'=>'暂无数据']);
        $re['Card_portrait'] = getUserCardInfo($mid,'Card_portrait');
        //优先使用非红包池
        $where['Blance'] = ['>',0];
        $where['Nums'] = ['>',0];
        $where['State'] = ['=',1];
        $order = 'Type asc,Addtime desc';
        //$field = 'Redenvelopes_id,Message';
        $field = '*';
        //检测用户是否有可用和可领取红包
        $R_num = 0;
        $R_state = false;
        $msg = '读取成功';
        $code = 10002;
        if($sid) 
        $re['cotype'] = 'code';//区分查询和领取的区别
        if($rid){//指定获取某个红包
            $count = Db::name('redenvelopes_code')->where(array('Redenvelopes_id'=>$rid,'User_id'=>$uid))->count();
            $where['Redenvelopes_id'] = ['=',$rid];
            $result = Db::name('redenvelopes')->where($where)->find();
            if(!$result || !Db::name('redenvelopes_list')->where(array('Redenvelopes_id'=>$rid))->find()){
                $re['i_r'] = 1;
                $msg = '红包已经被领光了';
            }else{
                // $count = Db::name('redenvelopes_code')->where(array('Redenvelopes_id'=>$rid,'User_id'=>$uid))->count();
                $R_num = $count;
                if($uid == $sid){
                    if($R_num < 2){
                        $re['i_r'] = 2;
                        $re['Message'] = $result['Message'];
                        $R_state = true;
                        $code = '10001';
                    }else{
                        $re['i_r'] = 3;
                        $msg = '这个红包你已经领过了';
                    }
                }else{
                    if($R_num < 1){
                        $re['i_r'] = 4;
                        $re['Message'] = $result['Message'];
                        $R_state = true;
                        $code = '10001';
                    }else{
                        if($R_num > 1){
                             $re['i_r'] = 5;
                            $msg = '这个红包你已经领过了';                 
                        }else{
                            $re['i_r'] = 6;
                            $msg = '这个红包你已经领过一次了';
                        }
                    }
                }
                $re['rid'] = $rid;
        }
    }else{
        if($result = judgeUserWhenRedenvelopesCode($uid,$where,$order,$field)){
            $R_num = $result['num'];
            if($R_num == 1){
                $re['i_r'] = 7;
                $msg = '这个红包你已经领过一次了';
            }else{
                $re['i_r'] = 8;
                $R_state = true;
                $re['Message'] = $result['msg'];
                $code = '10001';
            }
            $re['Message'] = $result['msg'];
                $re['rid'] = $result['rid'];
        }
	}
        $re['Redpack_State'] = $R_state;
        $re['Redpack_num'] = $R_num;
        // $re['Redpack_Tips'] = $msg;
        return json_encode(['code'=>$code,'msg'=>$msg,'data'=>$re]);
    }
     //领红包
    public function getRandomRedenvelopeCodeLimit()
    {
       if(!$uid = $this->WxApp_User_Id)
        return json_encode(['code'=>10003,'msg'=>'登陆超时']);
        $data = input('post.');
        if(empty($data['uid']) || !$data['uid'] || empty($data['mid']) || !$data['mid'])
        return json_encode(['code'=>10002,'msg'=>'参数错误']);
        $uid = $data['uid'];
        $mid = $data['mid'];
		if(getUserInfo($uid,'State') != 1)
		return json_encode(['code'=>10002,'msg'=>'领取失败']);
		$rid = !empty($data['rid'])?$data['rid']:'';
        $where['User_id'] = ['=',$mid];
        $where['State'] = ['=',1];
        $where['Nums'] = ['>',0];
        $where['Blance'] = ['>',0];
        $orde ='Addtime asc';
        $data['cotype'] = 'code';//区分查询和领取的区别
        $R_state = false;
        $R_num = 1;
        $msg = '';
        if($rid){//指定获取某个红包
            $where['Redenvelopes_id'] = ['=',$rid];
            if(!$arr = Db::name('redenvelopes')->where($where)->find())
            return json_encode(['code'=>10002,'msg'=>'红包已经被抢光','data'=>$data]);
        }else{
			//随机获取一条
            if(!$arr = Db::name('redenvelopes')->where($where)->orderRaw('rand()')->find())
            return json_encode(['code'=>10002,'msg'=>'红包已经被抢光','data'=>$data]);
        }
        $rid = $arr['Redenvelopes_id'];
        $R_num = judgeUserAppointRedenvelopesCode($uid,$rid);//查询指定红包用户
        if($R_num >1)
        return json_encode(['code'=>10002,'msg'=>'红包已经被抢光','data'=>$data]);
        $type = !empty($data['type'])?$data['type']:'';//获取红包方式，默认为随机获取
        $blance = $arr['Blance'];//红包余额
        $amount = 0.01;//默认领取金额
        $when['Redenvelopes_id'] = ['=',$rid];
        $rc = getUserCardInfo($uid);
        if($rc && ($rc['Wechat'] && $rc['Realname'] && $rc['Phone'])){
            if($type == 1){ //缘分值获取
                $fate_val = getMatchingFateValue($uid,$mid);//获取缘分值
                if($fate_val>0){
                    $when['Fate'] = ['gt',0];
                    $when['Fate'] = ['elt',$fate_val];
                    $torder = 'Fate desc';
                    $rb =  Db::name('redenvelopes_list')->where($when)->order($torder)->find();
                }else{
                    $torder = 'Amount asc';
                    $rb =  Db::name('redenvelopes_list')->where($when)->order($torder)->find();
                }
            }else{  //随机获取
                $rb = Db::name('redenvelopes_list')->where($when)->orderRaw('rand()')->find();
            }
            $data['Integrity'] = 1;//资料完整度
            
        }else{//资料不完善
            $data['Integrity'] = 0;//资料完整度
            $torder = 'Amount asc';
            $rb = Db::name('redenvelopes_list')->where($when)->order($torder)->find();
        }
        if(!$rb)
        return json_encode(['code'=>10002,'msg'=>'红包已经被抢光','data'=>$data]);
        $id = $rb['id'];
        $amount = $rb['Amount'];
        if($amount>$blance)
        $amount = $blance;
        $amount = round($amount,2);//预防出现多位小数
        $t_mat = ($blance*100 - $amount*100)/100;
        //开始录入
        if($result = $this->_generateRedenvelopeCodeOrderOne($uid,$id,$rid,$amount,$t_mat)){
            $data['Redpack_num'] = $R_num*1+1;
            $data['Redpack_State'] = $R_state;
            if($amount == 0){
                $data['Redpack_Tips'] ='很遗憾，没有抢到红包，再接再厉';
            }else{
                 $data['Amount'] = $amount;
                 $data['Message'] = $arr['Message'];
                 if($data['Integrity'] == 0){
                     $data['Redpack_Tips'] ='听说完善名片能提高手气哦';
                 }
            }
            return json_encode(['code'=>10001,'msg'=>'领取成功','data'=>$data]);
        }
        return json_encode(['code'=>10002,'msg'=>'很遗憾，没有抢到红包','data'=>$data]);
        
    }

    //查询当前红包被领取记录
    public function getAppointRedenvelopeCodeList()
    {
        if(!$uid = $this->WxApp_User_Id)
        return json_encode(['code'=>10003,'msg'=>'登陆超时']);
        $data = input('post.');
        if(empty($data['uid']) || !$data['uid'] || empty($data['rid']) || !$data['rid'])
        return json_encode(['code'=>10002,'msg'=>'参数错误']);
        $rid = $data['rid'];
        $page = !empty($data['page'])?$data['page']:1;
        $pagesize = !empty($data['pagesize'])?$data['pagesize']:6;
        if($arr = gteCountRedenvelopesCodeSingle($rid,$page,$pagesize))
        return json_encode(['code'=>10001,'msg'=>'读取成功','data'=>$arr]);
        return json_encode(['code'=>10002,'msg'=>'没有更多了']);
    }

    //创建红包订单
    private function _generateRedenvelopeOrder($uid,$order_id,$Fate_amount,$amount,$num,$type,$msg='')
    {
        $data = array();
        Db::startTrans();
        try{
            $time = time();
            $arr = [
                'User_id'=>$uid,
                'Redenvelopes_id'=>$order_id,
                'Amount'=>$amount,
                'Blance'=>$amount,
                'Message'=>$msg,
                'Nums'=>$num,
                'State'=>2,
                'Addtime'=>$time,    
                'Type'=>$type,    
            ]; 
        if(Db::name('redenvelopes')->insert($arr)){
            for($i=0;$i<count($Fate_amount);$i++){
                $data[$i] = [
                    'Redenvelopes_id'=>$order_id,
                    'Fate'=>$Fate_amount[$i]['key'],
                    'Amount'=>$Fate_amount[$i]['value'],    
                ];
            }       
            Db::name('redenvelopes_list')->insertAll($data);
            Db::commit();
            return $arr;
        }
             
        }catch(\Exception $e){
            Db::rollback();
            return false;
        }
    }

    //创建红包领取订单
    private function _generateRedenvelopeCodeOrderOne($uid,$id,$rid,$amount,$t_mat)
    {
        $time = time();
        $where['Redenvelopes_id'] = ['=',$rid];
        $where['State'] = ['=',1];
		$where['Nums'] = ['>',0];
		// $where['Blance'] = ['>=',$amount];
        Db::startTrans();
        try{
            if(Db::name('redenvelopes')->where($where)->update(array('Blance'=>$t_mat))){
                if($t_mat == 0){
                    Db::name('redenvelopes_list')->where(array('Redenvelopes_id'=>$rid))->delete();
                }else{
                    Db::name('redenvelopes_list')->where(array('Redenvelopes_id'=>$rid,'id'=>$id))->delete();
                }
                $arr = [
                    'User_id'=>$uid,
                    'Redenvelopes_id'=>$rid,
                    'Amount'=>$amount,
                    'Addtime'=>$time,        
                ];
                if(Db::name('redenvelopes_code')->insert($arr)){
                    Db::name('user')->where(array('User_id'=>$uid))->Inc('Smallchange',$amount)->update();
                    Db::commit();
                    return $arr;
                } 
            }         
            return false;
        }catch(\Exception $e){
            Db::rollback();
            return false;
        }
        
    }

    //我收发红包记录
    public function getRedenvelopeReceiveList()
    {
        if(!$uid = $this->WxApp_User_Id)
        return json_encode(['code'=>10003,'msg'=>'登陆超时']);
        $data = input('post.');
        if(empty($data['uid']) || !$data['uid'] || empty($data['type']) || !$data['type'])
        return json_encode(['code'=>10002,'msg'=>'参数错误']);
        $uid = $data['uid'];
        $type = $data['type'];
        $page = !empty($data['page'])?$data['page']:1;
        $pagesize = !empty($data['pagesize'])?$data['pagesize']:12;
        $where['User_id'] = ['=',$uid];
        $order = 'Addtime desc';
        $file = 'id,Addtime,Amount,Redenvelopes_id';
        if($type == '1'){ //我发出的红包
            $where['State'] = ['=',1];
            $table = 'redenvelopes';
			$file .=',User_id,Nums';
        }elseif($type == '2'){ //我收到的红包
            $table = 'redenvelopes_code';
        }else{
            return json_encode(['code'=>10002,'msg'=>'类型参数错误']);
        }
        // $field = 'a.Addtime,a.Redenvelopes_id,a.Amount,a.User_id,b.Username,b.Head_portrait,b.Card_portrait';
        // $re = Db::name($table)->alias('a')->join('user b','a.User_id = b.User_id')->where(array('a.User_id'=>$uid))->field($field)->page($page)->limit($pagesize)->select();
        $re = getRedenvelopesReceiveList($table,$where,$order,$page,$pagesize,$file);
        if($re){
            foreach($re as $r=>$e){
                if($table == 'redenvelopes_code' ){
                    $user_id = getRedenvelopesInfo($e['Redenvelopes_id'],'User_id');
                }else{
					$user_id = $e['User_id'];
					$re[$r]['Code_num'] = getRedenvelopesCodeCount($e['Redenvelopes_id']);
				}
                $uf = getUserInfo($user_id,'');
                $re[$r]['Message'] = getRedenvelopesInfo($e['Redenvelopes_id'],'Message');
                $re[$r]['Username'] = $uf['Username'];
                $re[$r]['Head_portrait'] = $uf['Head_portrait'];
                $re[$r]['Card_portrait'] = getUserCardInfo($user_id,'Card_portrait');
                $re[$r]['format_addtime'] = getFormatTime($e['Addtime']);
            }
            return json_encode(['code'=>10001,'msg'=>'获取数据成功','data'=>$re]);
        }
        return json_encode(['code'=>10002,'msg'=>'没有更多了']);
       
    }

    //收我红包的记录
    public function getRedenvelopeCodePassiveList()
    {
        if(!$uid = $this->WxApp_User_Id)
        return json_encode(['code'=>10003,'msg'=>'登陆超时']);
        $data = input('post.');
        if(empty($data['uid']) || !$data['uid'])
        return json_encode(['code'=>10002,'msg'=>'参数错误']);
        $uid = $data['uid'];
        $mid = !empty($data['mid'])?$data['mid']:'';
        $page = !empty($data['page'])?$data['page']:1;
        $pagesize = !empty($data['pagesize'])?$data['pagesize']:12;
        if(empty($data['rid']) || !$data['rid']){
            if(!$ids = getUserRedenvelopesCodeList($mid))
            return json_encode(['code'=>10002,'msg'=>'暂无数据']);
        }else{
            $ids = $data['rid'];
        }
        $where['a.Redenvelopes_id'] = ['in',$ids];
        $field = 'a.id,a.Redenvelopes_id,a.User_id,a.Addtime,a.Amount,b.Username,b.Head_portrait';
        $order = 'a.Addtime desc';
        if($re = Db::name('redenvelopes_code')->alias('a')->field($field)->join('user b','b.User_id=a.User_id')->where($where)->page($page)->limit($pagesize)->order($order)->select()){
            foreach($re as $r=>$e){
                $re[$r]['format_addtime'] = getFormatTime($e['Addtime']);
            }
            return json_encode(['code'=>10001,'msg'=>'获取数据成功','data'=>$re]);
        }
        return json_encode(['code'=>10002,'msg'=>'没有更多了']);
    }

	//红包池列表
    public function getRedenvelopeAvailableList()
    {
        if(!$uid = $this->WxApp_User_Id)
        return json_encode(['code'=>10003,'msg'=>'登陆超时']);
        $data = input('post.');
        if(empty($data['uid']) || !$data['uid'])
        return json_encode(['code'=>10002,'msg'=>'参数错误']);
		$uid = $data['uid'];
        $page = !empty($data['page'])?$data['page']:1;
        $pagesize = !empty($data['pagesize'])?$data['pagesize']:9999;
		$order = 'Addtime desc,Amount desc';
		$where['a.Nums'] = ['>',0];
		$where['a.Blance'] = ['>',0];
		$where['a.State'] = ['=',1];
        //显示存在的
		//$where['a.Type'] = ['=',2];//只显示开放性的
		$file = 'a.User_id,a.Redenvelopes_id,a.Amount,a.Blance,a.Nums,a.Addtime,a.Message,b.Username,b.Head_portrait';
		if($re = Db::name('redenvelopes')->alias('a')->where($where)->join('user b','a.User_id = b.User_id')->field($file)->order($order)->page($page)->limit($pagesize)->select()){
			foreach($re as $r=>$e){
                $uf = getUserInfo($e['User_id'],'');
                $re[$r]['format_addtime'] = getFormatTime($e['Addtime']);
                $re[$r]['Username'] = $uf['Username'];
                $re[$r]['Head_portrait'] = $uf['Head_portrait'];
				$re[$r]['word_time'] = conversionTime($e['Addtime']);
                $re[$r]['Tcnums'] = getRedenvelopesListCount($e['Redenvelopes_id']);
				$re[$r]['Redbagnums'] = judgeUserAppointRedenvelopesCode($uid,$e['Redenvelopes_id']);
            }
            return json_encode(['code'=>10001,'msg'=>'获取数据成功','data'=>$re]);
		}
        return json_encode(['code'=>10002,'msg'=>'没有更多了','data'=>$re]);
    }

    //红包达人榜
    public function getRedenvelopeRankingList()
    {
        if(!$uid = $this->WxApp_User_Id)
        return json_encode(['code'=>10003,'msg'=>'登陆超时']);
        $data = input('post.');
        if(empty($data['uid']) || !$data['uid'] || empty($data['type']) || !$data['type'])
        return json_encode(['code'=>10002,'msg'=>'参数错误']);
        $type = $data['type'];
        $page = !empty($data['page'])?$data['page']:1;
        $pagesize = !empty($data['pagesize'])?$data['pagesize']:9999;
        $pagestart = ($page*1-1)*$pagesize;
        $file = 'User_id';
        if($type == 1){ //发红包榜
            $where = 'State = 1';
            $sql = "select $file,totalAmount,totalScore, rank from(select User_id,totalAmount,totalScore,if(@de > totalScore, @rank:=@rank+@num+1, @rank) rank,if(@de = totalScore, @num:=@num, @num:=0),@de:=totalScore  from(select @de:=0, @rank:=1, @num:=0,id,User_id,sum(Amount) totalAmount,count(User_id) totalScore from super_redenvelopes where $where group by User_id order by totalScore desc,totalAmount desc) tmp) tmp2 limit $pagestart,$pagesize";
        }elseif($type == 2){ //抢红包榜
            $where = '1=1';
            $sql = "select $file,totalAmount,totalScore, rank from(select User_id,totalAmount,totalScore,if(@de > totalScore, @rank:=@rank+@num+1, @rank) rank,if(@de = totalScore, @num:=@num, @num:=0),@de:=totalScore  from(select @de:=0, @rank:=1, @num:=0,id,User_id,sum(Amount) totalAmount,count(User_id) totalScore from super_redenvelopes_code where $where group by User_id order by totalScore desc,totalAmount desc) tmp) tmp2 limit $pagestart,$pagesize";
        }
		//$sql = 'SELECT*, COUNT(User_id)  AS count FROM super_redenvelopes WHERE State = 1 GROUP BY User_id ORDER BY COUNT(User_id) DESC';
		if($re = Db::query($sql)){
			foreach($re as $r=>$e){
                $uf = getUserInfo($e['User_id'],'');
                $re[$r]['format_addtime'] = getFormatTime($uf['Addtime']);
                $re[$r]['Username'] = $uf['Username'];
                $re[$r]['Head_portrait'] = $uf['Head_portrait'];
            }
            return json_encode(['code'=>10001,'msg'=>'获取数据成功','data'=>$re]);
		}
		return json_encode(['code'=>10001,'msg'=>'获取数据成功','data'=>$re]);
    }

    //创建红包领取订单
    private function _generateRedenvelopeCodeOrder($uid,$red_id,$t_mat,$amount,$fat_val)
    {
        $time = time();
        $where['Redenvelopes_id'] = ['=',$red_id];
        $where['State'] = ['=',1];
		$where['Nums'] = ['>',0];
		$where['Blance'] = ['>=',$amount];
        Db::startTrans();
        try{
            if(Db::name('redenvelopes')->where($where)->update(array('Blance'=>$t_mat,'Fate_amount'=>$fat_val))){
                $arr = [
                    'User_id'=>$uid,
                    'Redenvelopes_id'=>$red_id,
                    'Amount'=>$amount,
                    'Addtime'=>$time,        
                ];
                if(Db::name('redenvelopes_code')->insert($arr) && Db::name('user')->where(array('User_id'=>$uid))->Inc('Smallchange',$amount)->update()){
                    Db::commit();
                    return $arr;
                }
            }         
            return false;
        }catch(\Exception $e){
            Db::rollback();
            return false;
        }
        
    }

    //创建提现记录
    private function _generateCashOrder($uid,$order_id,$amount)
    {
         Db::startTrans();
        try{
            $time = time();
            $arr = [
                'User_id'=>$uid,
                'Cash_id'=>$order_id,
                'Amount'=>$amount,
                'State'=>1,
                'Addtime'=>$time,        
            ];
            if(Db::name('Cash')->insert($arr)){
				Db::name('user')->where(array('User_id'=>$uid))->Dec('Smallchange',$amount)->Inc('Cash_amount',$amount)->update(array('Cash_time'=>$time));
                Db::commit();
                return true;
            }
            return false;
        }catch(\Exception $e){
            Db::rollback();
            return false;
        }
    }

}
